package com.wex.cookbook.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wex.cookbook.entity.Userinfo;
import com.wex.cookbook.exception.BizAssertUtils;
import com.wex.cookbook.mapper.UserinfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.wex.cookbook.constant.RoleEnum.RoleEnum.ADMIN;
import static com.wex.cookbook.constant.RoleEnum.RoleEnum.USER;

/**
 * @author : wex
 * @createTime : 2023/10/17 11:03
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserinfoMapper userinfoMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        LambdaQueryWrapper<Userinfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Userinfo::getUsername, s);
        Userinfo userinfo = userinfoMapper.selectOne(lambdaQueryWrapper);
        BizAssertUtils.notNull(userinfo,"账号或密码错误");

        List<GrantedAuthority> authorities = new ArrayList<>();
        if(userinfo.getRole() == 1) {
            //管理员
            authorities.add(new SimpleGrantedAuthority(ADMIN.getMsg()));
        } else {
            //普通用户
            authorities.add(new SimpleGrantedAuthority(USER.getMsg()));
        }

        String password = userinfo.getPassword();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        password = bCryptPasswordEncoder.encode(password);
        return new User(userinfo.getUsername(),password,authorities);
    }
}
